<template>
    <el-dialog width="35%" v-model="dialogVisible" title="预约服务" :before-close="handleClose">
        <el-form ref="formData" :model="formdata">
            <el-form-item label="预约人" label-width="27%">
                <el-input v-model="name" autocomplete="off" style="width: 70%" disabled />
            </el-form-item>
            <el-form-item label="联系电话" label-width="27%">
                <el-input v-model="telephone" autocomplete="off" style="width: 70%" disabled />
            </el-form-item>
            <el-form-item label="服务类别" label-width="27%">
                <el-cascader v-model="selectedOptions" :options="cascaderOptions" :props="cascaderProps"
                    :load="loadChildren" @change="handleChange" clearable lazy placeholder="选择服务类别"
                    style="width: 70%" />
            </el-form-item>
            <el-form-item label="预约服务日期" label-width="27%">
                <el-date-picker v-model="formdata.reserveDate" type="date" placeholder="选择预约日期"
                    :disabledDate="hiredateDisabledDate" :shortcuts="hiredateShortcuts" format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD" style="width: 70%" />
            </el-form-item>
            <el-form-item label="服务地点" label-width="27%">
                <el-input v-model="formdata.serviceAddress" autocomplete="off" style="width: 70%" />
            </el-form-item>
            <el-form-item label="预约详情" label-width="27%">
                <el-input v-model="formdata.orderDetail" placeholder="简要描述预约详情" autocomplete="off" style="width: 70%" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="canelDialog">取消</el-button>
                <el-button type="primary" @click="save" :icon="Promotion"> 保存 </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, watchEffect } from 'vue'
import { storeToRefs } from "pinia";
import { useServicetypeStore } from "../../../stores/servicetype.js";
import { ElMessage } from 'element-plus'
const servicetypeStore = useServicetypeStore()
const { dialogVisible, formdata, cascaderOptions } = storeToRefs(servicetypeStore)

// 获取用户信息
const userStr = localStorage.getItem('user')
let uId = null, name = null, telephone = null

if (userStr) {
    try {
        const userData = JSON.parse(userStr)
        uId = userData.id
        name = userData.name
        telephone = userData.telephone
    } catch (error) {
        console.error('解析用户数据失败:', error)
        ElMessage.error('获取用户信息失败')
        servicetypeStore.dialogVisible = false
    }
} else {
    ElMessage.warning('请先登录')
    servicetypeStore.dialogVisible = false
}

// 级联选择器的props  
const cascaderProps = {
    value: 'id', // 选项中用于表示值的字段名  
    label: 'serviceName', // 选项中用于表示标签的字段名  
    children: 'children', // 选项中用于表示子选项的字段名  
    leaf: 'leaderId',
    lazy: true, // 开启懒加载  
    lazyLoad(node, resolve) {
        // 当节点被展开时，会调用此方法  
        // 这里我们调用 serviceTypeStore 的 loadChildrenCategories 方法  
        servicetypeStore.loadChildrenCategories(node.value).then(children => {
            // 加载完成后，调用 resolve 方法并传入子选项数组  
            resolve(children);
        });
    },
};

const selectedOptions = ref([])
let isDefault = true;

// 监听 typeB 和 typeS 的变化  
watchEffect(() => {
    if (isDefault) {
        // 假设 typeB 和 typeS 是 reactive 对象，并且它们有 id 属性  
        if (servicetypeStore.typeB && servicetypeStore.typeS) {
            // console.log(servicetypeStore.typeB);
            selectedOptions.value = [servicetypeStore.typeB.id, servicetypeStore.typeS.id];
            console.log(selectedOptions.value);
        }
    }
    else {
        // selectedOptions.value = selectedOptions.value
        console.log(selectedOptions.value);
    }
});

// 组件挂载后加载父类别  
onMounted(() => {
    servicetypeStore.loadFatherCategories()
});

//获取当前反馈日期和时间
function dateFormat() {
    var now = new Date()
    var year = now.getFullYear()
    var month = now.getMonth() + 1 < 10 ?
        '0' + (now.getMonth() + 1) : now.getMonth() + 1
    var day = now.getDate() < 10 ? '0' + now.getDate() : now.getDate()
    var hour = now.getHours() < 10 ? '0' + now.getHours() : now.getHours()
    var minute = now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes()
    var second = now.getSeconds() < 10 ? '0' + now.getSeconds() : now.getSeconds()
    servicetypeStore.formdata.orderDate = year + '-' + month + '-' + day
    servicetypeStore.formdata.orderTime = hour + ":" + minute + ":" + second
}

const save = () => {
    if (!uId) {
        ElMessage.warning('请先登录')
        return
    }
    if (!selectedOptions.value || selectedOptions.value.length !== 2) {
        ElMessage.warning('请选择服务类别')
        return
    }
    if (!formdata.value.reserveDate) {
        ElMessage.warning('请选择预约日期')
        return
    }
    if (!formdata.value.serviceAddress) {
        ElMessage.warning('请输入服务地点')
        return
    }

    dateFormat()
    servicetypeStore.formdata = {
        ...servicetypeStore.formdata,
        uId: parseInt(uId),
        typeBId: parseInt(selectedOptions.value[0]),
        typeSId: parseInt(selectedOptions.value[1]),
        reserveDate: formdata.value.reserveDate,
        serviceAddress: formdata.value.serviceAddress,
        orderDetail: formdata.value.orderDetail || '',
        orderState: 0
    }
    console.log('准备提交的订单数据:', servicetypeStore.formdata)
    servicetypeStore.toOrder()
}


//定义日历的禁用日期计算属性
const hiredateDisabledDate = (time) => time.getTime() < new Date().getTime();
//定义日期的快捷键 快速选择
const hiredateShortcuts = [
    {
        text: '明天',
        value: () => {
            let now = new Date().getTime();
            now += 86400000;
            return new Date().setTime(now);
        }
    }, {
        text: '后天',
        value: () => {
            let now = new Date().getTime();
            now += 86400000 * 2;
            return new Date().setTime(now);
        }
    }, {
        text: '7天后',
        value: () => {
            let now = new Date().getTime();
            now += 86400000 * 7;
            return new Date().setTime(now);
        }
    }
]

const handleChange = () => {
    isDefault = false
}

const canelDialog = () => {
    servicetypeStore.dialogVisible = false
    servicetypeStore.formdata = {}
}
const handleClose = () => {
    canelDialog()
    isDefault = true
}
</script>